//
//  UINavigationBar+Awesome.m
//  AFNetworking
//
//  Created by huang on 2018/9/29.
//

#import "UINavigationBar+Awesome.h"
#import <objc/runtime.h>

#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

static char overlayKey;

@implementation UINavigationBar (Awesome)

#pragma mark - 底部线
#pragma mark 底部线颜色
- (void)hs_setBottomLineColor:(UIColor *)lineColor
{
    [self setShadowImage:[UINavigationBar imageWithColor:lineColor]];
}

- (void)hs_setBottomLineHidden:(BOOL)hidden
{
    UIImageView *lineImageView = [self findNavigationBarBlackLineWithView:self];
    lineImageView.hidden = hidden;
}

#pragma mark 找到导航条下面那条黑线
- (UIImageView *)findNavigationBarBlackLineWithView:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findNavigationBarBlackLineWithView:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

#pragma mark 根据颜色值生成图片
+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, 0.5, 0.5);
    UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRect:rect];
    roundedRect.lineWidth = 0;
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0f);
    [color setFill];
    [roundedRect fill];
    [roundedRect stroke];
    [roundedRect addClip];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [image resizableImageWithCapInsets:UIEdgeInsetsZero];
}

#pragma mark - 背景颜色
- (UIView *)overlay
{
    return objc_getAssociatedObject(self, &overlayKey);
}

- (void)setOverlay:(UIView *)overlay
{
    objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)hs_setBackgroundColor:(UIColor *)backgroundColor
{
    if (!self.overlay && self.subviews.count > 0) {
        [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        
        CGFloat topHeight = ([UIScreen mainScreen].bounds.size.height == 812 || [UIScreen mainScreen].bounds.size.height == 896)? 44:20;
        
        self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + topHeight)];
        self.overlay.userInteractionEnabled = NO;
        self.overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [[self.subviews firstObject] insertSubview:self.overlay atIndex:0];
    }
    
    self.overlay.backgroundColor = backgroundColor;
}

- (void)hs_setNavigationBackgroundAlpha:(CGFloat)alpha
{
    // 移除overlay
    [self removeOverlay];
    
    if (self.subviews.count > 0) {
        [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        
        // _UIBarBackground
        UIView *barBackgroundView = [[self subviews] objectAtIndex:0];
        // UIImageView
        UIImageView *backgroundImageView = [[barBackgroundView subviews] objectAtIndex:0];
        if (self.isTranslucent) {
            if (backgroundImageView != nil && backgroundImageView.image != nil) {
                barBackgroundView.alpha = alpha;
            } else {
                // UIVisualEffectView
                UIView *backgroundEffectView = [[barBackgroundView subviews] objectAtIndex:1];
                if (backgroundEffectView != nil) {
                    backgroundEffectView.alpha = alpha;
                }
            }
        } else {
            barBackgroundView.alpha = alpha;
        }
    }
    
    // 对导航栏下面那条线做处理
    self.clipsToBounds = alpha == 0;
}

- (void)hs_setTranslationY:(CGFloat)translationY
{
    self.transform = CGAffineTransformMakeTranslation(0, translationY);
}

- (void)hs_setElementsAlpha:(CGFloat)alpha
{
    [[self valueForKey:@"_leftViews"] enumerateObjectsUsingBlock:^(UIView *view, NSUInteger i, BOOL *stop) {
        view.alpha = alpha;
    }];
    
    [[self valueForKey:@"_rightViews"] enumerateObjectsUsingBlock:^(UIView *view, NSUInteger i, BOOL *stop) {
        view.alpha = alpha;
    }];
    
    UIView *titleView = [self valueForKey:@"_titleView"];
    titleView.alpha = alpha;
    [[self subviews] enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:NSClassFromString(@"UINavigationItemView")]) {
            obj.alpha = alpha;
        }
        if ([obj isKindOfClass:NSClassFromString(@"_UINavigationBarBackIndicatorView")]) {
            obj.alpha = alpha;
        }
    }];
}

- (void)hs_reset
{
    [self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    
    [self removeOverlay];
}

- (void)removeOverlay
{
    if (self.overlay) {
        [self.overlay removeFromSuperview];
        self.overlay = nil;
    }
}

#pragma mark - 设置状态
#pragma mark 设置为 transparent
- (void)hs_makeTransparent
{
    [self setTranslucent:YES];
    [self hs_setBottomLineHidden:YES];
    [self setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.backgroundColor = [UIColor clearColor];
    self.shadowImage = [UIImage new];
}

#pragma mark 设置为 default
- (void)hs_makeDefault
{
    [self setTranslucent:YES];
    [self hs_setBottomLineHidden:NO];
    [self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.backgroundColor = nil;
    self.shadowImage = nil;
}

@end
